//
//  PotraitInteractiveController.m
//  UIViewControllerTransitionDemo
//
//  Created by Guo Rui on 2017/7/6.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "PotraitInteractiveController.h"

@interface PotraitInteractiveController ()
@property (weak, nonatomic) UIViewController *viewController;
@property (assign, nonatomic) BOOL interactiving;
@end

@implementation PotraitInteractiveController

- (instancetype)initWithViewController:(UIViewController *)viewController {
    if (self = [super init]) {
        self.viewController = viewController;
        
        UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
        [self.viewController.view addGestureRecognizer:gesture];
    }
    return self;
}

- (void)panGestureRecognizer:(UIPanGestureRecognizer *)pan {
    CGFloat y = [pan translationInView:pan.view].y;
    
    if (y < 0) {
        return;
    }
    
    CGFloat progress = y / 200;
    
    progress = MAX(0, MIN(1, progress));
    
    NSLog(@"%lf, %lf", progress, y);
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {
            self.interactiving = YES;
            [self.viewController dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [self updateInteractiveTransition:progress];
        }
            break;
        case UIGestureRecognizerStateCancelled:
        {
            self.interactiving = NO;
            [self cancelInteractiveTransition];
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            self.interactiving = NO;
            if (progress > .2f) {
                [self finishInteractiveTransition];
            }
            else {
                [self cancelInteractiveTransition];
            }
        }
            break;
        default:
            break;
    }
}

@end
